<template>
  <ArtSearchBar ref="searchBarRef" v-model="formData" :items="formItems" :rules="rules" @reset="handleReset"
    @search="handleSearch">
  </ArtSearchBar>
</template>

<script setup lang="ts">
interface Props {
  modelValue: Record<string, any>
  departments?: Array<{ dept_code: string; dept_name: string }>
  roles?: Array<{ id: number; name: string }>
  salers?: Array<{ id: string; name: string }>
}
interface Emits {
  (e: 'update:modelValue', value: Record<string, any>): void
  (e: 'search', params: Record<string, any>): void
  (e: 'reset'): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 表单数据双向绑定
const searchBarRef = ref()
const formData = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 校验规则
const rules = {
  // userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
}

// 动态 options
const statusOptions = ref<{ label: string; value: string; disabled?: boolean }[]>([])
const deptOptions = computed(() =>
  (props.departments || []).map((d) => ({ label: d.dept_name, value: d.dept_code }))
)
const salerOptions = computed(() =>
  (props.salers || []).map((s) => ({ label: s.name, value: s.id }))
)
const roleOptions = computed(() => (props.roles || []).map((r) => ({ label: r.name, value: r.id })))

// 模拟接口返回状态数据
function fetchStatusOptions(): Promise<typeof statusOptions.value> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' },
      ])
    }, 1000)
  })
}

onMounted(async () => {
  statusOptions.value = await fetchStatusOptions()
})

// 表单配置
const formItems = computed(() => [
  {
    label: '用户名',
    key: 'username',
    type: 'input',
    placeholder: '请输入用户名',
    clearable: true
  },
  {
    label: '邮箱',
    key: 'email',
    type: 'input',
    props: { placeholder: '请输入邮箱' }
  },
  {
    label: '姓名',
    key: 'name',
    type: 'input',
    props: { placeholder: '请输入姓名' }
  },
  {
    label: '关联人员',
    key: 'person_id',
    type: 'select',
    props: { placeholder: '关联人员', options: salerOptions.value, filterable: true }
  },
  {
    label: '部门',
    key: 'department',
    type: 'select',
    props: {
      placeholder: '请输入部门',
      options: deptOptions.value,
      filterable: true
    }
  },
  {
    label: '状态',
    key: 'status',
    type: 'select',
    props: {
      placeholder: '请选择状态',
      options: statusOptions.value
    }
  }
])

// 事件
function handleReset() {
  console.log('重置表单')
  emit('reset')
}

async function handleSearch() {
  await searchBarRef.value.validate()
  emit('search', formData.value)
  console.log('表单数据', formData.value)
}
</script>
